package com.snail.app.gather.service;

import com.alibaba.fastjson.JSON;
import com.snail.app.gather.entity.DataSyncSendPath;
import com.snail.app.gather.entity.DataSyncTriggerInfo;
import com.snail.common.toolUtil.HttpUtil;
import com.snail.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @description
 * @date 2021/9/10
 * @autor houyanfeng
 */
@Service
@Transactional
public class DataPushCommonService {
    @Autowired
    private DataSyncTriggerInfoService dataSyncTriggerInfoService;
    @Autowired
    private DataSyncSendPathService dataSyncSendPathService;
    @Autowired
    private RawDataService rawDataService;

    public void fetchAndPushByAPI(Map<String,Object> params, String syncTriggerKey) throws Exception{
        fetchAndPushByAPI(params, syncTriggerKey, null);
    }
    /**
     * 将数据抓取并通过API上传平台
     * @param params Map<String,Object>传参：<br/>
     *               startTime 开始时间 yyyy-MM-dd；<br/>
     *               endTime 结束时间 yyyy-MM-dd；<br/>
     *               batch 数量条数
     * @param syncTriggerKey 触发条件类主键ID
     * @param sendPathId 发送路径ID
     * @throws Exception
     */
    public void pushByApi(Map<String,Object> params, String syncTriggerKey, String sendPathId) throws Exception {
        DataSyncSendPath sendPath = dataSyncSendPathService.getByKey(sendPathId);
        fetchAndPushByAPI(params, syncTriggerKey, sendPath);
    }
    /**
     * 将数据抓取并通过API上传平台
     * @param params Map<String,Object>传参：<br/>
     *               startTime 开始时间 yyyy-MM-dd；<br/>
     *               endTime 结束时间 yyyy-MM-dd；<br/>
     *               batch 数量条数
     * @param syncTriggerKey 触发条件类主键ID
     * @throws Exception
     */
    public void fetchAndPushByAPI(Map<String,Object> params, String syncTriggerKey, DataSyncSendPath sendPath) throws Exception{
        boolean syncSuccess = true;
        List<DataSyncTriggerInfo> dataSyncTriggers= dataSyncTriggerInfoService.listById(syncTriggerKey);
        for (DataSyncTriggerInfo dataSyncTrigger : dataSyncTriggers) {
            if(sendPath==null){
                sendPath = dataSyncSendPathService.getByKey(dataSyncTrigger.getSendPathId());
            }
            String dataPushUrl = "http://" + sendPath.getSendIp() + ":" + sendPath.getSendPort() + "/" + sendPath.getSendUrl();
            List<Map<String, Object>> dataMaps = rawDataService.listChangeRawData(params, dataSyncTrigger);
            //分批次发送，降低每次数据长度，每次发送10条数据
            Map<String, Object> sendMsg = new HashMap<>();
            sendMsg.put("orgId", dataSyncTrigger.getOrg());
            sendMsg.put("dataType", dataSyncTrigger.getTableName());
            sendMsg.put("operation", dataSyncTrigger.getId().getSyncType());
            sendMsg.put("syncId", dataSyncTrigger.getId().getId());
            List<Map<String, Object>> batchMaps = new ArrayList<>();
            for (Map<String, Object> dataMap : dataMaps) {
                batchMaps.add(dataMap);
                if (batchMaps.toString().length() > 20 * 1024) {//20个字节左右发送一次
                    sendMsg.put("data", batchMaps);
                    String reResult = HttpUtil.postByJson(dataPushUrl, JSON.toJSONString(sendMsg));
                    if (reResult != null && reResult.length() > 0) {
                        Map<String, Object> reMap = JSON.parseObject(reResult, Map.class);
                        if (!StringUtil.isEmpty(reMap.get("code")) && Integer.valueOf(reMap.get("code").toString()) == 200) {
                        } else {
                            syncSuccess = false;
                        }
                    }
                    batchMaps = new ArrayList<>();
                }
            }
            if (batchMaps.size() > 0) {
                sendMsg.put("data", batchMaps);
                String reResult = HttpUtil.postByJson(dataPushUrl, JSON.toJSONString(sendMsg));
                if (reResult != null && reResult.length() > 0) {
                    Map<String, Object> reMap = JSON.parseObject(reResult, Map.class);
                    if (!StringUtil.isEmpty(reMap.get("code")) && Integer.valueOf(reMap.get("code").toString()) == 200) {
                    } else {
                        syncSuccess = false;
                    }
                }
            }
            if (syncSuccess) {
                if (StringUtil.isEmpty(params.get("startTime"))) {//指定时间更新不需要改最后更新时间字段
                    if ("updatetime".equals(dataSyncTrigger.getMode()) && dataMaps.size() > 0) {//触发方式为更新时间
                        Map<String, Object> lastDataMap = dataMaps.get(dataMaps.size() - 1);
                        String updateTimeField = dataSyncTrigger.getField();
                        if (updateTimeField.contains(".")) {
                            updateTimeField = updateTimeField.substring(updateTimeField.indexOf(".") + 1);
                        }
                        String lastUpdateTime = lastDataMap.get(updateTimeField.toLowerCase()).toString();
                        if (lastUpdateTime.length() >= 19) {
                            dataSyncTrigger.setData(lastUpdateTime.substring(0, 19));//截止到秒
                        }
                    }
                }
                dataSyncTrigger.setLastSyncTime(new Date());
                dataSyncTriggerInfoService.save(dataSyncTrigger);
            }
        }
    }




}
